/**
 * 
 */
package chapter05;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

import chapter04.SleepUtils;

/**
 * 10-11
 * 背景：
 * 1、AQS提供"排他锁"和"共享锁"
 * 排他锁：有3个方法（acquire、tryAcquireNacos、acquireInterruptibly）
 * 共享锁：有3个方法（acquireShared、tryAcquireSharedNanos、acquireSharedInterruptibly)
 * 2、Lock接口的2种常见模版lock方式
 *
 *
 * 功能：AQS的"共享锁"的测试
 * 观察结果：一次打印2个，说明有2个线程同时获取到锁
 */
public class TwinsLockTest {

    public static void main(String[] args) {
        new TwinsLockTest().test();
    }

    public void test() {
        final Lock lock = new TwinsLock();

        // 内部类
        class Worker extends Thread {
            public void run() {
                while (true) {
                    lock.lock();
                    try {
                        SleepUtils.second(1);
                        System.out.println(Thread.currentThread().getName());
                        SleepUtils.second(1);
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }
        // 启动10个线程
        for (int i = 0; i < 10; i++) {
            Worker w = new Worker();
            w.setDaemon(true);
            w.start();
        }
        // 每隔1秒换行
        for (int i = 0; i < 10; i++) {
            SleepUtils.second(1);
            System.out.println();
        }
    }
}
